<template>
  <div id="tableConfig">

    <div class="columnsInfo">
      <h4>{{$t('transmit.fieldInfo')}}</h4>
      <el-form :model="exportObject" :rules="rules" ref="ruleForm" :inline="true" label-width="100px" class="demo-ruleForm" >
        <!-- 选择【字段CODE】
        <el-form-item label="字段CODE" prop="fieldCodeList" class="base-width-25">
          <el-input disabled type="textarea" autosize v-model="exportObject.fieldCodeList"></el-input>
        </el-form-item> -->
        <!-- 选择【字段名称】
        <el-form-item :label="$t('app.fieldName')" prop="fieldNameList"  class="base-width-25">
          <el-input disabled type="textarea" autosize v-model="exportObject.fieldNameList"></el-input>
        </el-form-item> -->
        <!-- 选择【导入类型】 -->
        <el-form-item :label="$t('app.importType')" prop="importType" class="base-width-25">
          <el-select v-model="exportObject.importType" :disabled="!newFlag" placeholder="" @change="validateImportType($event)">
            <el-option v-for="item in excelImportTypes" :key="item.code" :label="item.description" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('app.remark')" prop="remark" class="base-width-75">
          <el-input type="textarea" autosize v-model="exportObject.remark"></el-input>
        </el-form-item>

        <h4 style="margin-top: 25px">{{$t('other.definefield')}}<el-button type="primary" style="margin-left:20px" @click="add()">{{$t('bill.append')}}</el-button></h4>
        <!-- table表格-添加 -->
        <!-- table表格-列表 -->
        <el-table :data="tableData" border style="width: 100%" :key="keyFlag">
          <el-table-column align="center" type="index" :label="$t('app.index')" width="80"/>
          <el-table-column align="center" prop="fieldCode" :label="$t('app.fieldCode')">
            <template slot-scope="scope">
              <el-input v-show="scope.row.isEditor" class="item" v-model="scope.row.fieldCode" placeholder="" @change="verifyCode(scope.row)"></el-input>
              <span v-show="!scope.row.isEditor" class="txt">{{ scope.row.fieldCode }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="fieldName" :label="$t('app.fieldName')">
            <template slot-scope="scope">
              <el-input v-show="scope.row.isEditor" class="item" v-model="scope.row.fieldName" placeholder="" @change="verifyName(scope.row)"></el-input>
              <span v-show="!scope.row.isEditor" class="txt">{{ scope.row.fieldName }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="fieldWidth" :label="$t('app.fieldwidth')">
            <template slot-scope="scope">
              <el-input type="number" v-show="scope.row.isEditor" class="item" v-model="scope.row.fieldWidth" placeholder=""></el-input>
              <span v-show="!scope.row.isEditor" class="txt">{{ scope.row.fieldWidth }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="fieldDesc" :label="$t('app.fieldDesc')">
            <template slot-scope="scope">
              <el-input v-show="scope.row.isEditor" class="item" v-model="scope.row.fieldDesc" placeholder=""></el-input>
              <span v-show="!scope.row.isEditor" class="txt">{{ scope.row.fieldDesc }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" fixed="right" :label="$t('transmit.action')" width="200">
            <template slot-scope="scope">
              <el-button v-show="scope.row.isEditor" @click="save(scope.row, scope.$index)" type="text" size="small">{{$t("common.save")}}</el-button>
              <el-button v-show="!scope.row.isEditor" @click="edit(scope.row, scope.$index)" type="text" size="small">{{$t('security.edit')}}</el-button>
              <el-button @click="del(scope.row, scope.$index)" type="text" size="small">{{$t("common.delete")}}</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 保存|取消 -->
        <div class="btn_b">
          <el-button type="primary"  :disabled="!this.btnPermNameList.includes('EN02070104')&&!this.btnPermNameList.includes('WM03160104')" @click="saveObj('ruleForm')">{{$t("common.save")}}</el-button>
          <el-button :disabled="!this.btnPermNameList.includes('EN02070105')&&!this.btnPermNameList.includes('WM03160105')" @click="cancel">{{$t("common.cancel")}}</el-button>
        </div>
      </el-form>
    </div>
    <div class="columnsSetting">


    </div>
  </div>
</template>

<script>

import { insertExcelImportField, selectExcelImportFieldById, updateExcelImportField, getExcelImportType, validateImportType } from "@/api/transmit/transmit";
import baseMixin from "@/mixins/BaseMixin";

export default {
  mixins: [baseMixin],
  data() {
    return {
      // 主表
      exportObject: {
        fieldCodeList: undefined,
        fieldNameList: undefined,
        importType: undefined,
        remark: undefined,
        excelImportFieldDtls: undefined
      },
      // 子表
      tableData: [],
      newFlag: false,
      copyFlag: false,
      rules: {
        fieldCodeList: [{required: true, message: this.$inputPlease('app.fieldCode'), trigger: 'change'}],
        fieldNameList: [{required: true, message: this.$inputPlease('app.fieldName'), trigger: 'change'}],
        importType: [{required: true, message: this.$inputPlease('app.importType'), trigger: 'change'}]
      },
      keyFlag: true,
      excelImportTypes: []
    }
  },
  methods: {
    save(row, index) {
      index += 1;
      // 验证参数是否存在
      if (row.fieldCode === undefined) {
        let text = "请完善第【" + index + "】行的【字段code】";
        return this.$message.warning(text);
      }
      if (row.fieldName === undefined) {
        let text1 = "请完善第【" + index + "】行的【字段名称】";
        return this.$message.warning(text1);
      }
      if (row.fieldWidth === undefined) {
        let text2 = "请完善第【" + index + "】行的【字段宽度】";
        return this.$message.warning(text2);
      }
      row.isEditor = !row.isEditor;
      row.isSave = !row.isSave;
      this.keyFlag = !this.keyFlag;
    },
    edit(row, index) {
      console.log("edit下标 = %o， 对象信息 = %o", index, row.isEditor);
      row.isEditor = !row.isEditor;
      row.isSave = !row.isSave;
      this.keyFlag = !this.keyFlag;
    },
    del(row, index) {
      console.log("del下标 = %o， 对象信息 = %o", index, row);
      this.tableData.splice(index, 1);
    },
    add() {
      const obj = {
        index: this.tableData.length + 1,
        fieldCode: undefined,
        fieldName: undefined,
        fieldWidth: undefined,
        fieldDesc: undefined,
        isEditor: true,
        isSave: false
      };
      this.tableData.push(obj);
    },
    toSaveRequest() {
      console.log(this.exportObject);
      insertExcelImportField(this.exportObject).then(res => {
          let text = "保存成功!";
          this.$message.success(text);
          this.cancel();
        
      });
    },
    toEditRequest() {
      console.log(this.exportObject);
      updateExcelImportField(this.exportObject).then(res => {
          let text = "更新成功!";
          this.$message.success(text);
          this.cancel();
        
      });
    },
    logic() {

      // 验证是否为保存数据
      const subList = [];
      let codeStr = "";
      let nameStr = "";
      this.tableData.forEach((item, index) => {
        console.log("列表下标 = %o，对象信息 = %o", index, item);
        if (item.isSave) {
          codeStr += item.fieldCode + ', ';
          nameStr += item.fieldName + ', ';
          subList.push(item);
        }
      });

      // 转义-导入类型
      let importType = this.exportObject.importType;
      this.excelImportTypes.forEach((item) => {
        // console.log("a = %o, b = %o", importType, item.description);
        if (importType === item.description) {
          this.exportObject.importType = parseInt(item.code);
        }
      });

      if (subList.length !== 0) {
        this.exportObject.excelImportFieldDtls = subList;
        this.exportObject.fieldCodeList = codeStr;
        this.exportObject.fieldNameList = nameStr;
        if (this.newFlag) {
          // 新增逻辑
          this.toSaveRequest();
        } else {
          // 编辑逻辑
          this.toEditRequest();
        }
      } else {
        let text = "定义字段列表不能为空";
        return this.$message.warning(text);
      }
    },
    saveObj(ruleForm) {
      // 验证参数
      this.$refs[ruleForm].validate((valid) => {
        // 验证成功
        if (valid) {
          return this.logic();
        }
        // 验证失败
        else {
          let text = "参数不能为空";
          return this.$message.warning(text);
        }
      });
    },
    cancel() {
      this.$router.push({name: "excelImportField"})
    },
    getData() {
      try {
        console.log("getData = %o", this.selectData);
        selectExcelImportFieldById(this.selectData.id).then(res => {
            this.exportObject = res.data;
            this.exportObject.importType = this.exportObject.importType + ''
            // 转义-导入类型
            // let importType = this.exportObject.importType;
            // this.excelImportTypes.forEach((x) => {
            //   if (importType == x.code) {
            //     this.exportObject.importType = x.description;
            //   }
            // });

            // 复制清理主表id
            if (this.copyFlag) {
              this.exportObject.id = undefined;
            }
            this.tableData = this.exportObject.excelImportFieldDtls;
            this.tableData.forEach((item, index) => {
              item.isEditor = false;
              item.isSave = true;
              item.index = index + 1;

              // 复制清理子表id
              if (this.copyFlag) {
                item.defineId = undefined;
                item.id = undefined;
              }
            });
          
        })
      } catch (e) {
        this.$message.error(e);
      }
    },
    verifyName(e) {
      for (let i = 0; i < this.tableData.length - 1; i++) {
        let item = this.tableData[i];
        if (item.fieldName === e.fieldName) {
          let text = (i + 1) + "行存在重复的字段名称，请检查！";
          e.fieldName = undefined
          return this.$message.error(text);
        }
      }
    },
    verifyCode(e){
      for (let i = 0; i < this.tableData.length - 1; i++) {
        let item = this.tableData[i];
        if (item.fieldCode === e.fieldCode) {
          let text = (i + 1) + "行存在重复的字段Code，请检查！";
          e.fieldCode = undefined;
          return this.$message.error(text);
        }
      }
    },
    getExcelImportType() {
      getExcelImportType().then(res => {
        console.log("getExcelImportType = %o", res);
        this.excelImportTypes = res.list;
      });
    },
    validateImportType(e) {
      validateImportType(e).then(res => {
        console.log("验证导入类型 = %o， 结果为 = %o", e, res);
        console.log(typeof res.data);
          if (res.data) {
            let text = "导入数据类型已存在，请检查！";
            this.exportObject.importType = undefined;
            return this.$message.error(text);
          }
        
      });
    }
  },
  mounted() {

    this.newFlag = this.$store.state.newFlag;
    this.getExcelImportType();
    let query = this.$route.query;

    if (!this.newFlag) {
      this.selectData = this.$store.state.routeData;
      this.getData();
    }

    this.copyFlag = query.copy;
    if (this.copyFlag) {
      this.selectData = query.obj;
      this.getData();
    }
  }
}

</script>

<style lang="scss" scoped>

.demo-ruleForm {
  .el-select {
    height: 25px;

    ::v-deep .el-input {
      height: 25px;
    }
  }
}

.btn_b {
  width: 100%;
  text-align: center;
  margin-top: 16px;
}
</style>